package com.yym.selevlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet(value = "/download", name = "DownLoadServlet")
public class DownLoadServlet extends HttpServlet {


//    private String resourceLocatoin = "D:/nginx-server/images/abc.mp4";

    private String resourceLocatoin = "D:/nginx-server/nginx-1.17.2/images/";  //文件存放的地址

    /**
     * 下载是一个get请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // <a href="download?name=0dc725b1-5b12-4865-bbd0-2fbed66b9e7e.png">下载</a><br>
        //String name = req.getParameter("name");  //将要下载的文件名
        /***
        InputStream is = new FileInputStream(resourceLocatoin);
        String fileName = "上课视频.mp4";  //文件名

        byte[] bs = new byte[2048];
        int length = 0;

        // 处理中文文件下载的时候，浏览器显示乱码的问题
        String cnFileName = URLEncoder.encode(fileName, "utf-8");

        // 下载需要设置头信息, 是一种固定的模式
        resp.setHeader("Content-Disposition", "attachment; filename=" + cnFileName);

        ServletOutputStream servletOutputStream = resp.getOutputStream();

        while(-1 != (length = is.read(bs))) {
            servletOutputStream.write(bs, 0, length);
        }

        servletOutputStream.flush();
        servletOutputStream.close();
        is.close();
         */
        String name = req.getParameter("name");

        InputStream is = new FileInputStream(resourceLocatoin + name);

        byte[] bs = new byte[2048];
        int length = 0;

        // 处理中文文件下载的时候，浏览器显示乱码的问题
        String cnFileName = URLEncoder.encode(name, "utf-8");

        // 下载需要设置头信息, 是一种固定的模式
        resp.setHeader("Content-Disposition", "attachment; filename=" + cnFileName);

        /**
         * BufferedOutputStream   继承了 OutputStream
         * ServletOutputStream    继承了 OutputStream
         *
         * LinkedList   List
         * ArrayList    List
         */
        ServletOutputStream servletOutputStream = resp.getOutputStream();

        while(-1 != (length = is.read(bs))) {
            servletOutputStream.write(bs, 0, length);
        }

        servletOutputStream.flush();
        servletOutputStream.close();
        is.close();
    }
}
